/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utility;

import CA.Ca;
import Client.Client;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.w3c.dom.Document;

/**
 *
 * @author diego
 */
public class ComunicazioneBySignature {
    
    
    /*
     * Estraggo il PKCS10 dal Digital Signature
     */
    public static X509Certificate getCertificatefromDigSign(Document doc){

        // Stampo il Digest Signature recuperato
        //XMLUtility.printDocumentXML(doc);

        // Stampo il certificato stringa recuperato
        String certString = XMLUtility.getCertificatoString(doc);

        // Recupero PKCS10 da String
        byte[] decoded = Base64.decode(certString);
        PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(decoded);
   
        // Recupero il certificato X509 dalla stringa
        javax.security.cert.X509Certificate cert = crea509CertificateFromString(certString);
        X509Certificate cert_x = convert(cert);
        printX509Certificate(cert_x);                   

        return cert_x;
    }
    
  /*
     * Estraggo il PKCS10 dal Digital Signature e lo ritorno in tipo Stringa
     */
    public static String getStringPKCS10fromDigSign(Document doc){

        // Stampo il Digest Signature recuperato
        //printDocumentXML(doc);

        // Stampo il certificato stringa recuperato
        String pkcs10String = XMLUtility.getCertificatoString(doc);

        return pkcs10String;
    } 
    
    
    /*
     * Estraggo il PKCS10 dal Digital Signature
     */
    public static PKCS10CertificationRequest getPKCS10fromDigSign(Document doc){

        // Recupero la stringa di pkcs10
        String pkcs10String = getStringPKCS10fromDigSign(doc);

        // Recupero PKCS10 da String
        byte[] decoded = Base64.decode(pkcs10String);
        PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(decoded);

        return pkcs10;
    }
    
     
    
        /*
         * Stampa informazioni certificato
         */
        private static void printX509Certificate(X509Certificate cert){


            //Plug the Provider into the JCA/JCE
            Security.addProvider(new BouncyCastleProvider());

            try{


            String[] infos_emetteur = cert.getIssuerDN().getName().split("(=|, )", -1);
            String[] infos_titulaire = cert.getSubjectDN().getName().split("(=|, )", -1);

            System.out.println("CommonName : " + infos_titulaire[3]);
            System.out.println("EmailAdresse : " + infos_titulaire[1] + "\n");

            for (int i = 0; i < infos_emetteur.length; i += 2)
            {
                if (infos_emetteur[i].equals("C"))
                        System.out.println("CountryName : " + infos_emetteur[i + 1]);
                if (infos_emetteur[i].equals("O"))
                        System.out.println("OrganizationName : " + infos_emetteur[i + 1]);
                if (infos_emetteur[i].equals("CN"))
                        System.out.println("CommonName : " + infos_emetteur[i + 1]);
            }

            System.out.println("valido");
            System.out.println("dal : " + cert.getNotBefore());
            System.out.println("al : " + cert.getNotAfter());

            }
            catch(Exception exc){
            System.out.println("Couldn't instantiate X.509 certificate");
            return;
            }

        }
        
        
 
     /*
     * Funzione che converte un javax.security
     * in java.security
     */
    private static java.security.cert.X509Certificate convert(javax.security.cert.X509Certificate cert) {
        try {
            //System.out.println("..conversione a java da javax...");
            byte[] encoded = cert.getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf
                = java.security.cert.CertificateFactory.getInstance("X.509");
            //System.out.println("..conversione finita");
            return (java.security.cert.X509Certificate)cf.generateCertificate(bis);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (java.security.cert.CertificateException e) {
        }
        return null;
    }        
         
    
   /*
     * Crea certificato da stringa
     */
    private static javax.security.cert.X509Certificate crea509CertificateFromString(String certEntry) {  

        //System.out.println("input: "+certEntry);
        byte[] val_byte = certEntry.getBytes();
        //byte[] val_byte = Base64.decode(certEntry);
        javax.security.cert.X509Certificate x509 = null;
        try {
            x509 = javax.security.cert.X509Certificate.getInstance(val_byte);
        } catch (javax.security.cert.CertificateException ex) {
            System.err.println(ex);
        }
        //System.out.println(x509.getSerialNumber());
        //System.out.println("..Trasformo byte[] in javax");
        
        //X509Certificate certificato = Client.convert(x509);
        
        return x509;  
    }  
    
}
